<template>
  <div class="app-container">
    <div class="head-container">
      <!-- 搜索 -->
      <el-input v-model="listQuery.Filter" clearable size="small" placeholder="搜索..." style="width: 200px;"
        class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search"
        @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus"
        @click="handleCreate">新增</el-button>
      <el-button class="filter-item" size="mini" type="success" icon="el-icon-edit"
        @click="handleUpdate()">修改</el-button>
      <el-button slot="reference" class="filter-item" type="danger" icon="el-icon-delete" size="mini"
        @click="handleDelete()">删除</el-button>
        <el-button slot="reference" class="filter-item" type="warning" icon="el-icon-upload" size="mini"
        @click="exportExcel()">导出</el-button>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" @close="cancel()"
      :title="formTitle">
      <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="计划单号" prop="odd">
          <el-input v-model="form.odd" placeholder="请输入计划单号" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="计划数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入计划数量" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="已订货数量" prop="ordernumber">
          <el-input v-model="form.ordernumber" placeholder="请输入已订货数量" clearable
            :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="计划员" prop="planner">
          <el-input v-model="form.planner" placeholder="请输入计划员" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state" size="undefined">
            <el-radio v-for="(item, index) in stateOptions" :key="index" :label="item.value"
              :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计划类型" prop="types">
          <el-select v-model="form.types" placeholder="请输入计划类型" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in typesOptions" :key="index" :label="item.label"
              :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期" prop="projectdate">
          <el-date-picker  v-model="form.projectdate" :style="{width: '100%'}"
            placeholder="请输入计划日期" clearable></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="small" type="text" @click="cancel">取消</el-button>
        <el-button size="small" v-loading="formLoading" type="primary" @click="save">确认</el-button>
      </div>
    </el-dialog>
    <el-table ref="multipleTable" v-loading="listLoading" :data="list" size="small" style="width: 90%;"
      @sort-change="sortChange" @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <el-table-column type="selection" width="44px"></el-table-column>
      <el-table-column label="计划单号" prop="odd" align="center" />
      <el-table-column label="计划数量" prop="number" align="center" />
      <el-table-column label="已订货数量" prop="ordernumber" align="center" />
      <el-table-column label="计划员" prop="planner" align="center" />
      <el-table-column label="备注" prop="remark" align="center" />
      <el-table-column label="状态" prop="state" align="center" >
        <template v-slot="scope">
          <el-tag type="danger" v-if="scope.row.state ==true">未执行</el-tag>
          <el-tag type="warning" v-else-if="scope.row.state ==false">已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划类型" prop="types" align="center" />
      <el-table-column label="计划日期" prop="projectdate" align="center" >
        <template v-slot="scope">
          {{ scope.row.projectdate.replace('T', ' ').substring(0, 16).trim() }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" icon="el-icon-edit" />
          <el-button type="danger" size="mini" @click="handleDelete(row)" icon="el-icon-delete" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalCount>0" :total="totalCount" :page.sync="page"
      :limit.sync="listQuery.MaxResultCount" @pagination="getList" />
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import permission from "@/directive/permission/index.js";
import XLSX from 'xlsx';
// import axios from "@/axios";
const axios=require("axios");
const defaultForm = {
  id: null,
  odd: null,
  number: null,
  ordernumber: null,
  planner: null,
  remark: null,
  state: null,
  types: null,
  projectdate: null,
}
export default {
  name: 'Plan',
  components: {
    Pagination
  },
  directives: {
    permission
  },
  props: [],
  data() {
    return {
      rules: {
        odd: [{
          required: true,
          message: '请输入计划单号',
          trigger: 'blur'
        }],
        number: [{
          required: true,
          message: '请输入计划数量',
          trigger: 'blur'
        }],
        ordernumber: [{
          required: true,
          message: '请输入已订货数量',
          trigger: 'blur'
        }],
        planner: [{
          required: true,
          message: '请输入计划员',
          trigger: 'blur'
        }],
        remark: [{
          required: true,
          message: '请输入备注',
          trigger: 'blur'
        }],
        state: [{
          required: true,
          message: 'null',
          trigger: 'change'
        }],
        types: [{
          required: true,
          message: '请输入计划类型',
          trigger: 'change'
        }],
        projectdate: [{
          required: true,
          message: '请输入计划日期',
          trigger: 'change'
        }],
      },
      form: Object.assign({}, defaultForm),
      list: null,
      totalCount: 0,
      listLoading: true,
      formLoading: false,
      listQuery: {
        Filter: '',
        Sorting: '',
        SkipCount: 0,
        MaxResultCount: 10
      },
      page: 1,
      dialogFormVisible: false,
      multipleSelection: [],
      formTitle: '',
      isEdit: false,
      stateOptions: [{
        "label": "未执行",
        "value": "1"
      }, {
        "label": "已关闭",
        "value": "2"
      }],
      typesOptions: [{
        "label": "手工计划",
        "value": "1"
      }, {
        "label": "定时计划",
        "value": "2"
      }],
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList()
  },
  mounted() {},
  methods: {
    exportExcel() {
      axios({
        url: '/api/business/Plan/export-excels', // 请将此 URL 替换为你的服务器导出 Excel 的接口地址
        method: 'GET',
        responseType: 'blob'
      }).then((response) => {
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'exported_data.xlsx';
        a.click();
        window.URL.revokeObjectURL(url);
      }).catch((error) => {
        console.error('导出 Excel 时出错:', error);
      });
    
  },
    getList() {
      this.listLoading = true;
      this.listQuery.SkipCount = (this.page - 1) * this.listQuery.MaxResultCount;
      this.$axios.gets('/api/business/Plan', this.listQuery).then(response => {
        this.list = response.items;
        this.totalCount = response.totalCount;
        this.listLoading = false;
      });
    },
    fetchData(id) {
      this.$axios.gets('/api/business/Plan/' + id).then(response => {
        this.form = response;
      });
    },
    handleFilter() {
      this.page = 1;
      this.getList();
    },
    handleCreate() {
      this.formTitle = '新增采购计划';
      this.isEdit = false;
      this.dialogFormVisible = true;
    },
    handleDelete(row) {
      var params = [];
      let alert = '';
      if (row) {
        params.push(row.id);
        alert = row.name;
      }
      else {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: '未选择',
            type: 'warning'
          });
          return;
        }
        this.multipleSelection.forEach(element => {
          let id = element.id;
          params.push(id);
        });
        alert = '选中项';
      }
      this.$confirm('是否删除' + alert + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.posts('/api/business/Plan/delete', params).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleUpdate(row) {
      this.formTitle = '修改采购计划';
      this.isEdit = true;
      if (row) {
        this.fetchData(row.id);
        this.dialogFormVisible = true;
      }
      else {
        if (this.multipleSelection.length != 1) {
          this.$message({
            message: '编辑必须选择单行',
            type: 'warning'
          });
          return;
        }
        else {
          this.fetchData(this.multipleSelection[0].id);
          this.dialogFormVisible = true;
        }
      }
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.formLoading = true;
          this.form.roleNames = this.checkedRole;
          if (this.isEdit) {
            this.$axios.posts('/api/business/Plan/data-post', this.form).then(response => {
              this.formLoading = false;
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              });
              this.dialogFormVisible = false;
              this.getList();
            }).catch(() => {
              this.formLoading = false;
            });
          }
          else {
            this.$axios.posts('/api/business/Plan/data-post', this.form).then(response => {
              this.formLoading = false;
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              });
              this.dialogFormVisible = false;
              this.getList();
            }).catch(() => {
              this.formLoading = false;
            });
          }
        }
      });
    },
    sortChange(data) {
      const {
        prop,
        order
      } = data;
      if (!prop || !order) {
        this.handleFilter();
        return;
      }
      this.listQuery.Sorting = prop + ' ' + order;
      this.handleFilter();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    cancel() {
      this.form = Object.assign({}, defaultForm);
      this.dialogFormVisible = false;
      this.$refs.form.clearValidate();
    },
  }
}

</script>
<style>
</style>
